package com.yang.springcloud.controller;

import com.yang.springcloud.pojo.Dept;
import com.yang.springcloud.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门controller层，这里主要是提供restFul服务
 *
 * @author shiwen
 * @date 2020/10/12
 */
@RestController
public class DeptController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private IDeptService deptService;

    /**
     * 新增部门, 无法通过get的方式直接在url进行操作
     *
     * @param dept
     * @return
     */
    @PostMapping(value = "/dept/add")
    public boolean addDept(@RequestBody Dept dept) {
        return deptService.addDept(dept);
    }

    /**
     * 根据id获取部门
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/dept/queryById/{id}")
    public Dept queryDeptById(@PathVariable("id") long id) {
        return deptService.queryDeptById(id);
    }

    /**
     * 获取所有部门
     *
     * @returnxc
     */
    @GetMapping(value = "/dept/queryAll")
    public List<Dept> queryAll() {
        return deptService.queryAll();
    }

    @GetMapping(value = "/dept/queryNameById/{id}")
    public String queryNameById(@PathVariable("id") long id) {
        return deptService.getNameById(id);
    }

    // 获取注册进来的服务的信息
    @GetMapping("/dept/discovery")
    public Object discovery() {
        // 获取微服务列表清单
        List<String> services = discoveryClient.getServices();
        System.out.println("services：" + services);

        String description = discoveryClient.description();
        System.out.println("description：" + description);

        // 获取一个具体的服务信息, 通过具体的微服务id获取名字 【这里放的是applicationName, 就是注册到eureka的程序名】
        List<ServiceInstance> instances = discoveryClient.getInstances("springcloud-provider-dept");
        for (ServiceInstance serviceInstance : instances) {
            System.out.println(
                    serviceInstance.getHost() + "\t" +
                    serviceInstance.getPort() + "\t" +
                    serviceInstance.getUri() + "\t" +
                    serviceInstance.getServiceId()
            );
        }

        return this.discoveryClient;
    }

}